<template>
  <header>
    <div class="goback" @click="handleGoBack">
      <i class="icon iconfont icon-back"></i>
    </div>
    <div id="title-container">
      <div class="project-title" v-show="!isEditing" @click="handleClick">
        <span>{{ title }}</span>
      </div>
      <input
        type="text"
        class="project-title-input"
        ref="titleInput"
        v-if="isEditing"
        :value="title"
        @blur="handleTitleChange"
        @keyup.enter="handleTitleChange"
      />
    </div>
  </header>
</template>

<script>
export default {
  name: "page-header",
  props: {
    title: {
      type: String,
      default: "未命名",
    },
  },
  data() {
    return {
      isEditing: false,
    };
  },
  methods: {
    handleGoBack() {
      console.log("go back ...");
    },
    handleClick() {
      this.isEditing = true;
      this.$nextTick(() => {
        const oInput = this.$refs.titleInput;
        oInput.focus();
        oInput.select();
      });
    },
    handleTitleChange() {
      this.isEditing = false;
      const newTitle = this.$refs.titleInput.value;
      if (this.title !== newTitle) {
        // this.title = newTitle;
        // todo: 在父组件上处理 changeTitle 事件
        this.$emit("changeTitle", newTitle);
      }
    },
  },
};
</script>

<style>
header {
  width: 100%;
  height: 40px;
  padding-top: 10px;
  padding-left: 4px;

  display: flex;
}

.goback {
  width: 30px;
  height: 30px;
  border-radius: 2px;
  cursor: pointer;

  display: flex;
  justify-content: center;
  align-items: center;
}

.goback > .icon {
  font-size: 20px;
}

.goback:hover {
  background-color: #eeeeee;
}

#title-container {
  flex-grow: 1;
  height: 30px;
  font-size: 20px;
  font-weight: normal;
}

.project-title {
  display: inline-block;
  height: 100%;
  padding: 0 10px;
  border-radius: 2px;
  cursor: pointer;
}

.project-title:hover {
  background-color: #eeeeee;
}

.project-title-input {
  width: 200px;
  height: 30px;
  padding: 0 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none; /* 修改原有的边框样式 */
}
.project-title-input:focus,
.project-title-input:focus-visible {
  border: 1px solid #409eff;
  border-radius: 4px;
}
</style>
